<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Common\ProvinceController;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\City;
use App\Models\Product;
use App\Models\ProductSku;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Validation\Rule;

//商铺操作相关    todo    只有系统账号有权限操作商铺
class StoreController extends Controller
{
    //首页
    function index() {
        $provinces = DB::table('cities')->where('level','province')
            ->pluck('name')->toArray();
        return view('admin.store.index',['provinces'=>$provinces]);
    }

    //返回商铺列表数据  todo    添加商铺联系人电话
    function data(Request $request) {
        $model= new Store();
        $where = [];
        if ($title = $request->get('title')) {
            $where[] = ['title','like',$title . '%'];
        }
        if ($mobile = $request->get('mobile')) {
            $where[] = ['mobile','=',$mobile];
        }
        if ($start_time = $request->get('start_time')) {
            $where[] = ['created_at','>=',$start_time];
        }
        if ($end_time = $request->get('end_time')) {
            $where[] = ['created_at','<=',$end_time];
        }
        if ($status = $request->get('status')) {
            $where[] = ['status','=',$status];
        }
        if ($province = $request->get('province')) {
            $where[] = ['province','=',$province];
        }
        if ($city = $request->get('city')) {
            $where[] = ['city','=',$city];
        }
        $res = $model->get_store($where,$request->get('limit',LIMIT));

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        return Response::json($data);
    }

    function create() {
        //获取所有的省
        $province = new ProvinceController();
        $provinces = $province->provinces();
        return view('admin.store.create',['provinces' => $provinces]);
    }

    //保存商铺
    function store(Request $request) {
        //return substr($request->post('phone'),-6);

        $request->validate([
            'title' =>  ['required',Rule::unique('stores')->where(function ($query) use ($request) {
                return $query->where('province',$request->post('province'))
                             ->where('city',$request->post('city'))
                             ->where('district',$request->post('district'))
                             ->where('detailed_address',$request->post('detailed_address'));
            })],
            'nickname'  =>  'required',
            'phone'     =>  ['required','digits:11',Rule::unique('admins')],
            'service_mobile' => 'required|digits:11',
            'province'  =>  'required',
            'city'  =>  'required',
            'district'  =>  'required',
            'detailed_address'  =>  'required'
        ]);
        try{
            DB::beginTransaction();
            //创建商家后台登录账号
            //初始密码为手机号后6位
            $init_password = substr($request->post('phone'),-6);
            $admin = Admin::create([
                //手机号为登录账号
                'username'  =>  $request->post('phone'),
                'phone'     =>  $request->post('phone'),
                'password'  =>  $init_password,
                'nickname'  =>  $request->post('nickname')
            ]);
            Store::create([
                'title'             =>  $request->post('title'),
                'service_mobile'    =>  $request->post('service_mobile'),
                'province'          =>  $request->post('province'),
                'city'              =>  $request->post('city'),
                'district'          =>  $request->post('district'),
                'detailed_address'  =>  $request->post('detailed_address'),
                'admin_id'          =>  $admin->id,
                //后台添加的直接设置为开启，无需审核。
                'status'            =>  2
            ]);
            DB::commit();
            return Redirect::to(URL::route('store'))->with(['success'=>'添加成功']);
        }catch (Exception $exception){
            DB::rollBack();
            return Redirect::back()->withErrors('添加失败');
        }
    }

    function edit($store_id) {
        $store = Store::with('admin')->findOrFail($store_id);
        //获取所有的省
        $province = new ProvinceController();
        $provinces = $province->provinces();
        return view('admin.store.edit',['store'=>$store,'provinces'=>$provinces]);
    }

    function update(Request $request,$store_id) {
        $request->validate([
            'admin_id'  =>  ['required',Rule::exists('admins','id')->where(function ($query) use ($request) {
                $query->where('id',$request->post('admin_id'));
            })],
            'title' =>  ['required',Rule::unique('stores')->where(function ($query) use ($request) {
                return $query->where('province',$request->post('province'))
                    ->where('city',$request->post('city'))
                    ->where('district',$request->post('district'))
                    ->where('detailed_address',$request->post('detailed_address'));
            })->ignore($store_id)],
            'nickname'  =>  'required',
            'phone'     =>  ['required','digits:11',Rule::unique('admins')->where(function ($query) use ($store_id) {
                return $query->where('id', '<>' , Store::find($store_id)->admin_id);
            })],
            'service_mobile' => 'required|digits:11',
            'province'  =>  'required',
            'city'  =>  'required',
            'district'  =>  'required',
            'detailed_address'  =>  'required'
        ]);
        try{
            DB::beginTransaction();
            //更新商家后台登录账号信息
            Admin::where('id',$request->post('admin_id'))->update([
                //手机号为登录账号
                'username'  =>  $request->post('phone'),
                'phone'     =>  $request->post('phone'),
                'nickname'  =>  $request->post('nickname')
            ]);
            Store::where('id',$store_id)->update([
                'title'             =>  $request->post('title'),
                'service_mobile'    =>  $request->post('service_mobile'),
                'province'          =>  $request->post('province'),
                'city'              =>  $request->post('city'),
                'district'          =>  $request->post('district'),
                'detailed_address'  =>  $request->post('detailed_address'),
            ]);
            DB::commit();
            return Redirect::to(URL::route('store'))->with(['success'=>'修改成功']);
        }catch (Exception $exception){
            return Redirect::back()->withErrors('修改失败');
        }
    }
    //通过审核商铺
    function approve(Request $request) {
        //1、修改商铺状态
        Store::where('id',$request->post('id'))->update(['status'=>2]);
        //2、todo    后台创建商铺账号用以登录
        $data = [
            'code' => 0,
            'msg'   => '审核通过',
        ];
        return Response::json($data);
    }

    //关闭商铺
    function close(Request $request) {
        $store_id = $request->post('id');
        DB::beginTransaction();
        Store::where('id',$store_id)->update(['status'=>CLOSE]);
        $product_ids = Product::where('store_id',$store_id)->pluck('id');
        //下架该商铺的所有商品
        Product::where('store_id',$store_id)->delete();
        ProductSku::whereIn('product_id',$product_ids)->delete();
        DB::commit();
        $data = [
            'code' => 0,
            'msg'   => '关闭成功',
        ];
        return Response::json($data);
    }

    //开启关闭的商铺
    function open(Request $request) {
        $store_id = $request->post('id');
        DB::beginTransaction();
        Store::where('id',$store_id)->update(['status'=>OPEN]);
        $product_ids = Product::where('store_id',$store_id)->withTrashed()->pluck('id');
        //上架该商铺的所有商品
        Product::where('store_id',$store_id)->restore();
        ProductSku::whereIn('product_id',$product_ids)->restore();
        DB::commit();
        $data = [
            'code' => 0,
            'msg'   => '开启成功',
        ];
        return Response::json($data);
    }
}
